<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="订单编号" prop="orderSn">
        <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号" clearable size="small"/>
      </el-form-item>
      <el-form-item label="会员手机号" prop="receiverPhone">
        <el-input v-model="queryParams.receiverPhone" placeholder="请输入会员手机号" clearable size="small"/>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="订单状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 订单列表 -->
    <el-table v-loading="loading" :data="orderList" border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单编号" align="center" prop="orderSn" width="180"/>
      <el-table-column label="收件信息" align="center" min-width="200">
        <template #default="scope">
          <div>收件人: {{scope.row.receiverName}}</div>
          <div>电话: {{scope.row.receiverPhone}}</div>
          <div>地址: {{scope.row.receiverProvince}}{{scope.row.receiverCity}}{{scope.row.receiverDistrict}}{{scope.row.receiverDetailAddress}}</div>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" align="center" min-width="300">
        <template #default="scope">
          <div v-if="!scope.row.items || scope.row.items.length === 0" class="no-items">
            暂无商品信息
          </div>
          <div v-else v-for="item in scope.row.items" :key="item.id" class="order-item">
            <el-image :src="item.pic" :preview-src-list="[item.pic]" class="product-img"/>
            <div class="product-info">
              <div class="product-name">{{item.productName}}</div>
              <div class="product-sku" v-if="item.spData">{{item.spData}}</div>
              <div class="product-price">
                <span class="price">￥{{item.salePrice}}</span>
                <span class="quantity">x{{item.quantity}}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" width="150">
        <template #default="scope">
          <div>商品金额: ￥{{scope.row.totalAmount}}</div>
          <div>运费: ￥{{scope.row.freightAmount}}</div>
          <div class="amount">实付金额: ￥{{scope.row.payAmount}}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">
            {{statusMap[scope.row.status]}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <div class="operation-wrapper">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              link
              :icon="Van"
              size="small"
              @click="handleShip(scope.row)"
            >发货</el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              link
              :icon="CircleClose"
              size="small"
              @click="handleClose(scope.row)"
            >关闭</el-button>
            <el-button
              type="info"
              link
              :icon="EditPen"
              size="small"
              @click="handleNote(scope.row)"
            >备注</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 发货对话框 -->
    <el-dialog title="订单发货" v-model="shipDialogVisible" width="500px" append-to-body>
      <el-form ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="80px">
        <el-form-item label="物流公司" prop="deliveryCompany">
          <el-input v-model="shipForm.deliveryCompany" placeholder="请输入物流公司"/>
        </el-form-item>
        <el-form-item label="物流单号" prop="deliverySn">
          <el-input v-model="shipForm.deliverySn" placeholder="请输入物流单号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitShipForm">确 定</el-button>
          <el-button @click="cancelShip">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 备注对话框 -->
    <el-dialog title="订单备注" v-model="noteDialogVisible" width="500px" append-to-body>
      <el-form ref="noteFormRef" :model="noteForm" :rules="noteRules" label-width="80px">
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="noteForm.note" placeholder="请输入备内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitNoteForm">确 定</el-button>
          <el-button @click="cancelNote">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listOrder, shipOrder, updateOrderNote, closeOrder, exportOrder } from '@/api/order'
import { useRouter } from 'vue-router'
import { Van, CircleClose, EditPen } from '@element-plus/icons-vue'

const router = useRouter()

// 遮罩层
const loading = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 订单表格数据
const orderList = ref([])
// 日期范围
const dateRange = ref([])
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderSn: undefined,
  receiverPhone: undefined,
  status: undefined
})

// 状态数据字典
const statusOptions = [
  { value: 0, label: '待付款' },
  { value: 1, label: '待发货' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已关闭' }
]

// 状态映射
const statusMap = {
  0: '待付款',
  1: '待发货',
  2: '已发货',
  3: '已完成',
  4: '已关闭'
}

// 状态样式映射
const statusTypeMap = {
  0: 'info',
  1: 'warning',
  2: 'primary',
  3: 'success',
  4: 'danger'
}

// 发货对话框
const shipDialogVisible = ref(false)
const shipFormRef = ref(null)
const shipForm = reactive({
  orderId: undefined,
  deliveryCompany: undefined,
  deliverySn: undefined
})
const shipRules = {
  deliveryCompany: [
    { required: true, message: '请输入物流公司', trigger: 'blur' }
  ],
  deliverySn: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 备注对话框
const noteDialogVisible = ref(false)
const noteFormRef = ref(null)
const noteForm = reactive({
  orderId: undefined,
  note: undefined
})
const noteRules = {
  note: [
    { required: true, message: '请输入备注内容', trigger: 'blur' }
  ]
}

/** 查询订单列表 */
function getList() {
  loading.value = true
  listOrder(queryParams).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.orderSn = undefined
  queryParams.receiverPhone = undefined
  queryParams.status = undefined
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  handleQuery()
}

/** 导出按钮操作 */
function handleExport() {
  exportOrder(queryParams).then(response => {
    downloadExcel(response, `order_${new Date().getTime()}.xlsx`)
  })
}

/** 订单发货 */
function handleShip(row) {
  shipDialogVisible.value = true
  shipForm.orderId = row.id
}

/** 关闭订单 */
function handleClose(row) {
  ElMessageBox.confirm('确认要关闭该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    closeOrder(row.id).then(response => {
      ElMessage.success('关闭订单成功')
      getList()
    })
  }).catch(() => {})
}

/** 更新订单备注 */
function handleNote(row) {
  noteDialogVisible.value = true
  noteForm.id = row.id
  noteForm.note = row.note
}

/** 提交发货表单 */
function submitShipForm() {
  if (!shipFormRef.value) return
  shipFormRef.value.validate((valid) => {
    if (valid) {
      const { orderId, deliveryCompany, deliverySn } = shipForm
      shipOrder(orderId, deliveryCompany, deliverySn).then(response => {
        ElMessage.success('发货成功')
        shipDialogVisible.value = false
        getList()
      })
    }
  })
}

/** 提交备注表单 */
function submitNoteForm() {
  if (!noteFormRef.value) return
  noteFormRef.value.validate((valid) => {
    if (valid) {
      updateOrderNote(noteForm).then(response => {
        ElMessage.success('更新备注成功')
        noteDialogVisible.value = false
        getList()
      })
    }
  })
}

/** 取消发货 */
function cancelShip() {
  shipDialogVisible.value = false
  resetShipForm()
}

/** 取消备注 */
function cancelNote() {
  noteDialogVisible.value = false
  resetNoteForm()
}

/** 重置发货表单 */
function resetShipForm() {
  shipForm.orderId = undefined
  shipForm.deliveryCompany = ''
  shipForm.deliverySn = ''
  shipFormRef.value?.resetFields()
}

/** 重置备注表单 */
function resetNoteForm() {
  noteForm.id = undefined
  noteForm.note = ''
  noteFormRef.value?.resetFields()
}

/** 处理分页变化 */
function handlePagination(val) {
  queryParams.pageNum = val.page
  queryParams.pageSize = val.limit
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
.order-item:last-child {
  border-bottom: none;
}
.product-img {
  width: 80px;
  height: 80px;
  margin-right: 10px;
}
.product-info {
  flex: 1;
}
.product-name {
  font-size: 14px;
  margin-bottom: 5px;
}
.product-sku {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}
.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.price {
  color: #f56c6c;
  font-weight: bold;
}
.quantity {
  color: #999;
}
.amount {
  color: #f56c6c;
  font-weight: bold;
  margin-top: 5px;
}
.no-items {
  color: #999;
  text-align: center;
  padding: 20px;
}
.operation-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 5px;
}
.operation-wrapper .el-button {
  justify-content: flex-start;
  width: 100%;
  margin-left: 0;
  padding: 8px 15px;
}
.operation-wrapper .el-button:hover {
  background-color: var(--el-color-primary-light-9);
}
.operation-wrapper .el-button.el-button--danger:hover {
  background-color: var(--el-color-danger-light-9);
}
.operation-wrapper .el-button.el-button--info:hover {
  background-color: var(--el-color-info-light-9);
}
</style> 